import { createGridView, boundField, customField } from "myWuZhui";
import React = require("react");
import ReactDOM = require("react-dom");
import { UserService } from "admin/services/user";
import { FormValidator, rules as r } from "maishu-dilu";
import * as wuzhui from "maishu-wuzhui";
import * as chitu from "maishu-chitu";
import { PageProps } from "maishu-chitu-react";

// export default function (page: chitu.Page) {
//     ReactDOM.render(<EmployeePage />, page.element)
// }

interface State {
    currentEmployee: User,
    roles: Role[]
}

export default class EmployeePage extends React.Component<PageProps, State>{
    employeeTable: HTMLTableElement;
    dataSource: wuzhui.DataSource<User>;
    employeeDialog: HTMLElement;
    employee: User
    validator: FormValidator;

    constructor(props) {
        super(props)
        this.state = { currentEmployee: {} as User, roles: [] }
        let service = this.props.app.createService(UserService)
        service.roles().then(roles => {
            this.setState({ roles })
        })
    }
    showDialog(employee: User): void {
        // let employee: User = {} as User
        this.setState({ currentEmployee: employee })
        ui.showDialog(this.employeeDialog)
    }
    removeItem(employee: User) {

    }
    async save(): Promise<any> {
        if (!this.validator.check()) {
            return
        }
        let employee = this.state.currentEmployee
        if (employee.id)
            await this.dataSource.update(employee)
        else
            await this.dataSource.insert(employee)
        ui.hideDialog(this.employeeDialog)
    }
    componentDidMount() {
        this.validator = new FormValidator(this.employeeDialog,
            { name: 'mobile', rules: [r.required('请输入员工手机号'), r.mobile()] }
        )

        let self = this
        let service = this.props.app.createService(UserService)
        this.dataSource = new wuzhui.DataSource({
            primaryKeys: ['id'],
            async select() {
                let users = await service.applicationUsers()
                return { dataItems: users, totalRowCount: users.length };
            },
            async insert(item) {
                let { user_id } = await service.applicationAddUser(item.mobile, item.role_ids);
                item.id = user_id
            },
            async update(item) {
                return service.applicationUpdateUser(item.id, item.role_ids)
            }
        })
        createGridView({
            dataSource: this.dataSource,
            element: this.employeeTable,
            columns: [
                boundField<User>({ dataField: 'mobile', headerText: '手机', headerStyle: { width: '140px' } as CSSStyleDeclaration }),
                customField({
                    headerText: "角色",
                    createItemCell() {
                        let cell = new wuzhui.GridViewDataCell<User>({
                            render(dataItems, element) {
                                let value: string[] = dataItems.role_ids;
                                service.roles().then(roles => {
                                    let roleNames = roles.filter(r => value.indexOf(r.id) >= 0).map(o => o.name).join(',')
                                    element.innerHTML = roleNames
                                })
                            }
                        })

                        return cell
                    }
                }),
                customField({
                    headerText: '操作',
                    headerStyle: { textAlign: 'center', width: '120px' } as CSSStyleDeclaration,
                    itemStyle: { textAlign: 'center' } as CSSStyleDeclaration,
                    createItemCell(dataItem: User) {
                        let cell = new wuzhui.GridViewCell()
                        ReactDOM.render(<React.Fragment>
                            <button className="btn btn-info btn-minier"
                                onClick={() => self.showDialog(dataItem)}>
                                <i className="icon-pencil"></i>
                            </button>
                            <button className="btn btn-danger btn-minier"
                                onClick={() => self.removeItem(dataItem)}>
                                <i className="icon-remove"></i>
                            </button>

                        </React.Fragment>, cell.element)
                        return cell
                    }
                })
            ]
        })
    }
    render() {
        let { currentEmployee, roles } = this.state
        currentEmployee.role_ids = currentEmployee.role_ids || []
        return <React.Fragment>
            <ul key={10}>
                <li className="pull-right">
                    <button className="btn btn-sm btn-primary"
                        onClick={() => this.showDialog({} as User)}>
                        <i className="icon-plus" />
                        <span>添加角色</span>
                    </button>
                </li>
            </ul>
            <table key={20} ref={e => this.employeeTable = e || this.employeeTable}></table>
            <div className="modal fade" ref={e => this.employeeDialog = e || this.employeeDialog}>
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button" className="close"
                                onClick={() => ui.hideDialog(this.employeeDialog)}>
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h4 className="modal-title">添加员工</h4>
                        </div>
                        <div className="modal-body form-horizontal">
                            <div className="form-group">
                                <label className="col-sm-2 control-label">名称*</label>
                                <div className="col-sm-10">
                                    <input name="mobile" type="text" className="form-control"
                                        placeholder="请输入员工手机号"
                                        value={currentEmployee.mobile || ''}
                                        onChange={e => {
                                            currentEmployee.mobile = (e.currentTarget as HTMLInputElement).value;
                                            this.setState({ currentEmployee })
                                        }} />
                                </div>
                            </div>
                            <div className="form-group">
                                <label className="col-sm-2 control-label">角色</label>
                                <div className="col-sm-10" style={{ paddingTop: 10 }}>
                                    {roles.map(o =>
                                        <span key={o.id} className="checkbox" style={{ display: 'unset', paddingRight: 10 }}>
                                            <label>
                                                <input type="checkbox" value={o.id} checked={currentEmployee.role_ids.indexOf(o.id) >= 0}
                                                    onChange={e => {
                                                        if (e.target.checked) {
                                                            currentEmployee.role_ids.push(o.id)
                                                        }
                                                        else {
                                                            currentEmployee.role_ids = currentEmployee.role_ids.filter(id => id != e.target.value)
                                                        }
                                                        this.setState({ currentEmployee })

                                                    }} />{o.name}</label>
                                        </span>)}
                                </div>
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button name="cancel" type="button" className="btn btn-default"
                                onClick={() => ui.hideDialog(this.employeeDialog)}>
                                取消
                            </button>
                            <button name="ok" type="button" className="btn btn-primary"
                                ref={(e: HTMLButtonElement) => {
                                    ui.buttonOnClick(e, () => this.save())
                                }}>
                                确定
                    </button>
                        </div>
                    </div>
                </div>
            </div>
        </React.Fragment >
    }
}